using System;
using UnityEngine;
using System.Collections.Generic;
using Framework.Save;
using LitJson;
using TMPro;

namespace GameCore
{
    public class CraftingInventory : MonoBehaviour, IJsonSerializable
    {
        public string inventoryName;
        public int currentLevel = 0;
        public TMP_Text titleText;
        public ClickableObject upgradeButton;
        public TMP_Text buttonText;
        public List<IngredientGroup> upgradeMaterials;
        public GameObject levelMaxObject;

        private void Start()
        {
            upgradeButton.OnClick += Upgrade;
            Refresh();
        }

        private void Upgrade()
        {
            if (!upgradeMaterials[currentLevel].Match()) return;
            upgradeMaterials[currentLevel].gameObject.SetActive(false);
            currentLevel += 1;
        }

        private void Refresh()
        {
            upgradeMaterials.ForEach(m => m.gameObject.SetActive(false));
            if (currentLevel < upgradeMaterials.Count)
            {
                levelMaxObject.SetActive(false);
                upgradeMaterials[currentLevel].gameObject.SetActive(true);
                buttonText.text = upgradeMaterials[currentLevel].Match() ? "升级" : "材料不足";
                titleText.text = $"{inventoryName} : LV.{currentLevel}";
            }
            else
            {
                levelMaxObject.SetActive(true);
                buttonText.text = "已达最大等级";
                titleText.text = $"{inventoryName} : MAX";
            }
        }
        
        #if UNITY_EDITOR
        private void OnValidate()
        {
            Refresh();
        }
        #endif

        public JsonData Serialize()
        {
            var json = JsonUtil.NewObject();
            json["name"] = inventoryName;
            json["level"] = currentLevel;
            json["materials"] = JsonUtil.NewArray();
            foreach(var m in upgradeMaterials)
                json["materials"].Add(m.Serialize());
            return json;
        }

        public void Deserialize(JsonData data)
        {
            
        }
    }
}